package com.alipay.rebate.shop.service.admin.impl;

import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.ActivityProductMapper;
import com.alipay.rebate.shop.dao.mapper.CommissionLevelSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.UserGradeMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.helper.UserGradeBuilder;
import com.alipay.rebate.shop.model.ActivityProduct;
import com.alipay.rebate.shop.model.CommissionLevelSettings;
import com.alipay.rebate.shop.model.UserGrade;
import com.alipay.rebate.shop.pojo.usergrade.UserGradeReq;
import com.alipay.rebate.shop.pojo.usergrade.UserGradeRsp;
import com.alipay.rebate.shop.service.admin.UserGradeService;
import com.alipay.rebate.shop.utils.ListUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by CodeGenerator on 2019/08/16.
 */
@Service
@Transactional
public class UserGradeServiceImpl extends AbstractService<UserGrade> implements UserGradeService {

    private Logger logger = LoggerFactory.getLogger(UserGradeServiceImpl.class);
    @Resource
    private UserGradeMapper userGradeMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ActivityProductMapper activityProductMapper;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Resource
    private CommissionLevelSettingsMapper commissionLevelSettingsMapper;

    @Override
    public List<UserGrade> getAllSortByWeight() {
        return userGradeMapper.getAllSortByWeight();
    }

    @Override
    public void deleteUserGrade(Integer id) {
        userGradeMapper.deleteByPrimaryKey(id);
        userMapper.updateUserGradeToDefault(id);
        commissionLevelSettingsMapper.deleteByUserGradeId(id);
        List<ActivityProduct> activityProducts = activityProductMapper.selectByQualType(2);
        logger.debug("activityProducts is : {}",activityProducts);
        if(!ListUtil.isEmptyList(activityProducts)){
            activityProducts.forEach(activityProduct -> {
                String qualJson = activityProduct.getQualJson();
                Map<String,Object> map = null;
                try {
                    map = objectMapper.readValue(qualJson, Map.class);
                    String gradeLevel = String.valueOf(map.get("userLevel"));
                    // 如果原本不是默认等级, 那么更新为默认等级
                    if(!StringUtils.isEmpty(gradeLevel)  && !"1".equals(gradeLevel)
                        && String.valueOf(id).equals(gradeLevel)){
                        ActivityProduct np = new ActivityProduct();
                        np.setId(activityProduct.getId());
                        map.put("userLevel",1);
                        map.put("userLevelName","普通合伙人");
                        np.setQualJson(objectMapper.writeValueAsString(map));
                        activityProductMapper.updateByPrimaryKeySelective(np);
                    }
                } catch (IOException e) {
                    throw new BusinessException("内部错误",StatusCode.INTERNAL_ERROR);
                }
                logger.debug("map is: {}",map);
            });
        }
    }

    @Override
    public void addUserGrade(UserGradeReq req) {
        UserGrade userGrade = convert2UserGrade(req,new Date());
        userGradeMapper.insertSelective(userGrade);
        batchAddCommissionLevelSettings(req,userGrade);
    }

    @Override
    public void updateUserGrade(UserGradeReq req) {
        UserGrade userGrade = convert2UserGrade(req,new Date());
        userGradeMapper.updateByPrimaryKeySelective(userGrade);
        commissionLevelSettingsMapper.deleteByUserGradeId(req.getId());
        batchAddCommissionLevelSettings(req,userGrade);
    }

    @Override
    public UserGradeRsp userGradeDetail(Integer id) {
        UserGrade userGrade = userGradeMapper.selectByPrimaryKey(id);
        if(userGrade == null){
            throw new BusinessException("记录不存在",StatusCode.INTERNAL_ERROR);
        }
        List<CommissionLevelSettings> levelSettings =
            commissionLevelSettingsMapper.selectByUserGradeId(userGrade.getId());
        return UserGradeBuilder.convert2UserGradeRsp(userGrade,levelSettings);
    }

    private UserGrade convert2UserGrade(UserGradeReq req, Date createTime){
        UserGrade userGrade = new UserGrade();
        userGrade.setId(req.getId());
        userGrade.setGradeName(req.getGradeName());
        userGrade.setGradeWeight(req.getGradeWeight());
        userGrade.setFirstCommission(req.getFirstCommission());
        userGrade.setSecondCommission(req.getSecondCommission());
        userGrade.setThirdCommission(req.getThirdCommission());
        userGrade.setEnableCmlevelSettings(req.getEnableCmlevelSettings());
        userGrade.setCreateTime(createTime);
        userGrade.setUpdateTime(new Date());
        return userGrade;
    }

    private void batchAddCommissionLevelSettings(UserGradeReq req,UserGrade userGrade){
        if(ListUtil.isEmptyList(req.getLevelSettings())){
            return;
        }
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        CommissionLevelSettingsMapper settingsMapper =
            sqlSession.getMapper(CommissionLevelSettingsMapper.class);

        for(CommissionLevelSettings settings: req.getLevelSettings()){
            settings.setUserGradeId(userGrade.getId());
            Date date = new Date();
            settings.setCreateTime(date);
            settings.setUpdateTime(date);
            settingsMapper.insertSelective(settings);
        }
        sqlSession.flushStatements();
    }
}
